package hmis.pos.sys.shiro.myRealm;

import hmis.pos.Common.Util.JWTUtil;
import hmis.pos.sys.entity.SysUserEntity;
import hmis.pos.sys.repository.SysPermissionRepository;
import hmis.pos.sys.service.SysUserService;
import hmis.pos.sys.shiro.token.JWTToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Service
public class MyRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LogManager.getLogger(MyRealm.class);

    @Autowired
    private SysPermissionRepository sysPermissionRepository;

    private SysUserService sysUserService;

    @Autowired
    public void setSysUserService(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    /**
     * 必须重写，否则shiro会报错
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = JWTUtil.getUsername(principalCollection.toString());
        SysUserEntity entity = sysUserService.findByUsername(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        List<String> permissions = sysPermissionRepository.findPermissionsByRoleId(entity.getRoleId());
        Set<String> permission = new HashSet<>(permissions);
        simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) {
        String token = (String)auth.getCredentials();
        // 解密获得username，与数据库数据对比
        String username = JWTUtil.getUsername(token);
        if(username==null||!JWTUtil.verify(token,username)){
            throw new AuthenticationException("token错误或过期");
        }

        return new SimpleAuthenticationInfo(token,token,"my_realm");
    }
}
